package org;

import java.util.*;

public class Solution {

    public static void main(String[] args) {
        String[] strings={"i", "love", "leetcode", "i", "love", "coding"};

        Solution solution=new Solution();
        List<String> list = solution.topKFrequent(strings, 2);
        for (String temp:list){
            System.out.println(temp);
        }
    }

    public List<String> topKFrequent(String[] words, int k) {

        Map<String,Integer> map=new HashMap<>();

        for (String str :words){
            map.put(str,map.getOrDefault(str,0)+1);
        }
        List<String> rec = new ArrayList<String>();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            rec.add(entry.getKey());
        }
        Collections.sort(rec, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return map.get(o1).equals(map.get(o2)) ?o1.compareTo(o2):map.get(o2)-map.get(o1);
            }
        });
        return rec.subList(0, k);
    }

}
